package com.livesource.client.webservices.git;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.jsonp.client.JsonpRequestBuilder;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.livesource.client.LiveSourceGlobalVariables;
import com.livesource.client.model.entry.ProjectClass;
import com.livesource.client.model.project.Project;
import com.livesource.client.utilities.ConvertJson;
import com.livesource.client.utilities.FileExtensions;
import com.livesource.client.webservices.ConvertJsonpToJavaDocumentation;
import com.livesource.client.webservices.subversion.ConvertJsonpToFeatureFile;

public class RequestGitClassDocument {

	// http://livesourceagile.com:8080/LiveSourceWebServices/GetGitClassDocumentService
	// ?projectName=Jsonpfy
	// &filePath=src/com/jsonpfy/client/SaveLiveFeed.java

	private static String url = "http://livesourceagile.com:8080/LiveSourceWebServices/GetGitClassDocumentService";

	public static void getJsonpRequest(Project project, final ProjectClass file) {

		// String username = EncryptText.decrypt(GetCookies.getUsername(project
		// .getProjectID()));
		String username = null;

		// String password =
		// EncryptText.decrypt(GetCookies.getPassword(project.getProjectID()));
		String password = null;

		JsonpRequestBuilder jsonp = new JsonpRequestBuilder();

		jsonp.setTimeout(15000);

		String urlGet = url + "?projectName=" + project.getProjectID()
				+ "&filePath=" + file.toString();

		jsonp.requestObject(urlGet, new AsyncCallback<JavaScriptObject>() {

			public void onFailure(Throwable throwable) {

				System.out.println("Error: " + throwable);
			}

			public void onSuccess(JavaScriptObject feed) {

				JSONObject entry = new JSONObject(feed);

				ProjectClass projectClass = LiveSourceGlobalVariables.projectEntries
						.get(file.toString());

				projectClass.setFileContent(ConvertJson.convertToString(entry
						.get("fileContent")));

				String fileExtension = FileExtensions
						.getFileExtension(projectClass.toString());

				if (FileExtensions.EXTENSION_JAVA.equals(fileExtension)) {

					projectClass = ConvertJsonpToJavaDocumentation.convert(
							projectClass, entry);

				} else if (FileExtensions.EXTENSION_FEATURE
						.equals(fileExtension)) {

					projectClass = ConvertJsonpToFeatureFile.convert(
							projectClass, entry);
				}

				LiveSourceGlobalVariables.projectEntries.put(
						projectClass.toString(), projectClass);
			}
		});
	}
}
